#include "myhead.h"

/*
	五个线程分别代表五个不同的售票窗口
*/
int curnum=10; //当前票的数量

//定义互斥锁
pthread_mutex_t mymutex;

//定义一个条件变量
pthread_cond_t mycond;

void *win1(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mymutex);
		curnum--;  
		printf("窗口1卖出一张票，还剩下%d张票!\n",curnum);
		if(curnum<=0) //票卖完了
		{
			//阻塞当前窗口(线程)
			printf("窗口1阻塞在wait！\n");
			pthread_cond_wait(&mycond,&mymutex);
		}
		sleep(1);
		pthread_mutex_unlock(&mymutex);
		usleep(100);
	}
}
void *win2(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mymutex);
		curnum--; 
		printf("窗口2卖出一张票，还剩下%d张票!\n",curnum);
		if(curnum<=0) //票卖完了
		{
			//阻塞当前窗口(线程)
			printf("窗口2阻塞在wait！\n");
			pthread_cond_wait(&mycond,&mymutex); //先解锁，然后阻塞当前线程
		}
		sleep(1);
		pthread_mutex_unlock(&mymutex);
		usleep(100);
	}
}
void *win3(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mymutex);
		curnum--;
		printf("窗口3卖出一张票，还剩下%d张票!\n",curnum);
		if(curnum<=0) //票卖完了
		{
			//阻塞当前窗口(线程)
			printf("窗口3阻塞在wait！\n");
			pthread_cond_wait(&mycond,&mymutex);
		}
		sleep(1);
		pthread_mutex_unlock(&mymutex);
		usleep(100);
	}
}

void *win4(void *arg)
{
	while(1)
	{
		pthread_mutex_lock(&mymutex);
		curnum--;
		printf("窗口4卖出一张票，还剩下%d张票!\n",curnum);
		if(curnum<=0) //票卖完了
		{
			//阻塞当前窗口(线程)
			printf("窗口4阻塞在wait！\n");
			pthread_cond_wait(&mycond,&mymutex);
		}
		sleep(1);
		pthread_mutex_unlock(&mymutex);
		usleep(100);
	}
}
int main()
{
	//初始化锁
	pthread_mutex_init(&mymutex,NULL);
	
	//初始化条件变量
	pthread_cond_init(&mycond,NULL);
	pthread_t id1,id2,id3,id4;
	pthread_create(&id1,NULL,win1,NULL);
	pthread_create(&id2,NULL,win2,NULL);
	pthread_create(&id3,NULL,win3,NULL);
	pthread_create(&id4,NULL,win4,NULL);
	
	pthread_join(id1,NULL);
	pthread_join(id2,NULL);
	pthread_join(id3,NULL);
	pthread_join(id4,NULL);
}